<template>
	<div class="relative w-full h-full">
		<div ref="wrapRef" id="container" :style="{ height, width }">
			<div v-show="false">
				<div ref="infoLayerRef">
					<info-layer :site-data="siteData" @close="handleCloseInfoWindow" @handling="handling" />
				</div>
				<div ref="markerListLayerRef">
					<marker-list-layer :list="markerList" @close="handleCloseMarkerList" @handling="handlingMarkerList" />
				</div>
			</div>
		</div>
		<!-- 地图样式切换 -->
		<div class="absolute top-0 right-0 z-[99] text-[#000] text-xs">
			<div class="flex border-[#3ecafc] border-[1px] bg-white cursor-pointer">
				<div class="px-1" :class="{ 'bg-[#3ecafc]': mapStyle === 'normal', 'text-white': mapStyle === 'normal' }" @click="handleMapStyle('normal')">
					{{ t('analysis.classics') }}
				</div>
				<div
					class="px-1"
					:class="{ 'bg-[#3ecafc]': mapStyle === 'bdd9ba31ac1a7cb82320894e4c12eb08', 'text-white': mapStyle === 'bdd9ba31ac1a7cb82320894e4c12eb08' }"
					@click="handleMapStyle('bdd9ba31ac1a7cb82320894e4c12eb08')"
				>
					{{ t('analysis.blue') }}
				</div>
				<div
					class="px-1"
					:class="{ 'bg-[#3ecafc]': mapStyle === 'Satellite', 'text-white': mapStyle === 'Satellite' }"
					@click="handleMapStyle('Satellite')"
				>
					{{ t('analysis.satellite') }}
				</div>
			</div>
		</div>
		<!-- 处理 -->
		<handling-form-dialog ref="handlingFormDialogRef" @refresh="refresh" />
	</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import markerIcon_normal from '/@/assets/analysis/normal-icon.png';
import markerIcon_alarm from '/@/assets/analysis/alarm-icon.png';
import markerIcon_warning from '/@/assets/analysis/warning-icon.png';
import markerIcon_offline from '/@/assets/analysis/offline-icon.png';
import infoLayer from './infoLayer.vue';
import markerListLayer from './markerListLayer.vue';
import { mapPoint } from '/@/api/analysis/index';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const HandlingFormDialog = defineAsyncComponent(() => import('/@/views/alarm/alarmLogging/components/handlingForm.vue'));

const props = defineProps({
	width: {
		type: String,
		default: '100%',
	},
	height: {
		type: String,
		default: '100%',
	},
	zoom: {
		type: Number,
		default: 5,
	},
	latitude: {
		type: Number,
		default: 101.4327,
	},
	longitude: {
		type: Number,
		default: 33.37086,
	},
	styleId: {
		type: String,
	},
});

const wrapRef = ref<HTMLDivElement | null>(null);
const markerListLayerRef = ref<HTMLDivElement | null>(null);
const siteData = reactive({});
const infoLayerRef = ref();
const handlingFormDialogRef = ref();
const mapStyle = ref('bdd9ba31ac1a7cb82320894e4c12eb08');
const pointsList = ref([]);
const markerList = ref([]);
let map: any;
let cluster: any;
let Amap: any;
let infoWindow: any;
let markerListWindow: any;
async function initMap() {
	(window as any)._AMapSecurityConfig = { securityJsCode: '3e6cf3d22e1f6b3b31087119fd73d0ea' };
	AMapLoader.load({
		key: '61a2206220e92f8131d82b95b4c37918', // 申请好的Web端开发者Key，首次调用 load 时必填
		version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
		plugins: ['AMap.MarkerCluster'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
	})
		.then((AMap) => {
			Amap = AMap;
			map = new AMap.Map('container', {
				// 设置地图容器id
				viewMode: '3D', // 是否为3D地图模式
				zoom: 3, // 初始化地图级别
				center: [103.732739, 35.275814], // 初始化地图中心点位置
				// pitch: 6,
				// pitchEnable: false,
				// rotateEnable: false,
				zooms: [2, 28],
				mapStyle: 'amap://styles/bdd9ba31ac1a7cb82320894e4c12eb08',
				lang: 'en',
				// mapStyle: 'amap://styles/blue',
			});
			infoWindow = new AMap.InfoWindow({
				isCustom: true, //使用自定义窗体
				closeWhenClickMap: true,
				offset: new AMap.Pixel(14, -20),
				autoMove: true,
				anchor: 'bottom-center',
			});
			markerListWindow = new AMap.InfoWindow({
				isCustom: true, //使用自定义窗体
				closeWhenClickMap: true,
				offset: new AMap.Pixel(4, -28),
				autoMove: true,
				// anchor: 'middle-right',
			});
			markerListWindow.close();
			infoWindow.close();
			getDataList();
		})
		.catch((e) => {});
}

// 获取设备数据
const getDataList = () => {
	mapPoint().then((res) => {
		pointsList.value = res.data;
		addCluster(res.data);
	});
};
// 添加聚合标记
const addCluster = (list: any) => {
	cluster && cluster?.setData([]);
	let points: { lnglat: [string, string]; extrm: any }[] = [];
	let markers: any = [];
	for (let i = 0; i < list.length; i++) {
		const item = list[i];
		// 标记点
		points.push({
			lnglat: [item.longitude, item.latitude],
			extrm: item,
		});
		// 标记marker
		const mk = new Amap.Marker({
			icon: new Amap.Icon({
				size: new Amap.Size(32, 32),
				image: markerIcon_normal,
			}),
			position: new Amap.LngLat(item.longitude, item.latitude),
		});
		markers.push(mk);
	}
	cluster = new Amap.MarkerCluster(map, points, {
		clusterByZoomChange: true,
		renderMarker: _renderMarker,
	});
	cluster.on('click', (e: any) => {
		//此处是通过包含点的数量判断是否是聚合点
		if (e.clusterData.length <= 1) {
			return;
		}
		let curZoom = map.getZoom();
		if (curZoom > 7) {
			map.setFitView(e.marker);
			return;
		}
		if (curZoom < 20) {
			curZoom += 1;
		}
		map.setZoomAndCenter(curZoom, e.lnglat);
	});
	// map.setFitView(markers);
};
// 自定义非聚合点标记样式
const _renderMarker = (context: any) => {
	const { deviceState: state } = context.data[0].extrm;
	const mkIicon = new Amap.Icon({
		size: new Amap.Size(32, 32),
		image: state === 20 ? markerIcon_normal : state === 30 ? markerIcon_warning : state === 40 ? markerIcon_alarm : markerIcon_offline,
	});
	if (state === 30) {
		context.marker.setzIndex(parseInt(context.data[0].extrm.faultCreateTime));
	}
	if (state === 40) {
		context.marker.setzIndex(parseInt(context.data[0].extrm.alarmCreateTime));
	}
	const { installLocationId, latitude, longitude } = context.data[0].extrm;
	const cover_markers = pointsList.value.filter((d: any) => {
		return (d.installLocationId === installLocationId && installLocationId) || (d.latitude === latitude && d.longitude === longitude);
	});
	if (cover_markers.length > 1) {
		context.marker.setLabel({
			content: `<div class='px-1 text-primary'>设备：${cover_markers.length}台</div>`,
			direction: 'top',
			offset: new Amap.Pixel(0, -10),
		});
		context.marker.on('rightclick', () => {
			if (cover_markers.length > 1) {
				markerList.value = cover_markers;
				const markerList_content = unref(markerListLayerRef);
				markerListWindow.setContent(markerList_content);
				const pos = context.marker.getPosition();
				markerListWindow.open(map, pos);
			}
		});
	}
	context.marker.setIcon(mkIicon);
	context.marker.on('click', () => {
		try {
			markerListWindow.close();
			const content = unref(infoLayerRef);
			Object.assign(siteData, context.data[0].extrm);
			infoWindow.setContent(content);
			infoWindow.setAnchor('bottom-center');
			const pos = context.marker.getPosition();
			infoWindow.open(map, pos);
			// map.setCenter(context.marker.getPosition());
		} catch (err: any) {
			// useMessage().error(err.msg);
		}
	});
};
// 关闭信息窗口
const handleCloseInfoWindow = () => {
	infoWindow.close();
};
// 刷新标记点
const refresh = () => {
	infoWindow.close();
	getDataList();
};
// 切换地图样式
const handleMapStyle = (type: string) => {
	const layers = map.getLayers();
	if (type === mapStyle.value) return;
	if (type === 'Satellite') {
		layers.push(new Amap.TileLayer.Satellite(), new Amap.TileLayer.RoadNet());
		map.setLayers(layers);
	} else {
		const new_layers = layers.filter(
			(d: { CLASS_NAME: string }) => d.CLASS_NAME !== 'AMap.TileLayer.Satellite' && d.CLASS_NAME !== 'AMap.TileLayer.RoadNet'
		);
		map.setLayers(new_layers);
		let styleName = 'amap://styles/' + type;
		map.setMapStyle(styleName);
	}
	mapStyle.value = type;
};
const handling = (id: any, propcess: any) => {
	handlingFormDialogRef.value.openDialog(id, propcess);
};
//
const handleCloseMarkerList = () => {};
//
const handlingMarkerList = (item: any) => {
	const content = unref(infoLayerRef);
	Object.assign(siteData, item);
	infoWindow.setContent(content);
	infoWindow.setAnchor('bottom-center');
	const pos = new Amap.LngLat(item.longitude, item.latitude);
	infoWindow.open(map, pos);
};
onMounted(() => {
	initMap();
});

onUnmounted(() => {
	map?.destroy();
});
</script>
<style lang="scss" scoped>
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
:deep(.amap-marker-label) {
	border: unset;
	border-radius: 12px;
}
</style>
